<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>打字小游戏</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background-color: #f0f0f0; }
        #header { text-align: center; margin-bottom: 30px; }
        .game-menu { display: flex; justify-content: center; gap: 20px; margin-bottom: 30px; }
        .game-menu button { background: #007bff; color: #fff; border: none; border-radius: 5px; padding: 12px 28px; font-size: 18px; cursor: pointer; transition: background 0.2s; }
        .game-menu button.active, .game-menu button:hover { background: #0056b3; }
        #back-btn { background: #888; margin-bottom: 20px; }
        #back-btn:hover { background: #444; }
        .game-section { display: none; }
        .game-section.active { display: block; }
        /* 单词雨样式 */
        #wordrain-canvas { background: #222; display: block; margin: 0 auto 20px; border-radius: 8px; }
        #wordrain-input { width: 100%; padding: 10px; font-size: 18px; border-radius: 5px; border: 2px solid #007bff; margin-bottom: 10px; }
    </style>
</head>
<body>
    <div id="header">
        <!-- 返回主菜单按钮和标题 -->
        <button id="back-btn" onclick="location.href='main.html'">返回主菜单</button>
        <h1>打字小游戏</h1>
    </div>
    <div class="game-menu">
        <!-- 游戏菜单按钮，切换不同小游戏 -->
        <button id="btn-timed" onclick="showGame('timed')" class="active">限时打字</button>
        <button id="btn-wordrain" onclick="showGame('wordrain')">单词雨</button>
        <button id="btn-react" onclick="showGame('react')">反应速度测试</button>
        <button id="btn-chain" onclick="showGame('chain')">打字接龙</button>
        <button id="btn-clear" onclick="showGame('clear')">消除方块</button>
        <button id="btn-mole" onclick="showGame('mole')">打地鼠</button>
    </div>
    <!-- 各小游戏区域，默认只显示限时打字 -->
    <div id="timed" class="game-section active">
        <!-- 限时打字游戏区域 -->
        <h2>限时打字（1分钟）</h2>
        <div id="timed-exercise-container" style="background:#fff;padding:30px;border-radius:10px;box-shadow:0 0 10px rgba(0,0,0,0.1);">
            <div id="timed-target-text"></div>
            <textarea id="timed-input-text" placeholder="在这里输入上面的文字..." oninput="timedCheckInput()" disabled></textarea>
            <div style="display:flex;justify-content:space-around;margin-top:10px;">
                <div>剩余时间: <span id="timed-timer">60</span> 秒</div>
                <div>速度: <span id="timed-speed">0</span> 字/分钟</div>
                <div>准确率: <span id="timed-accuracy">0</span>%</div>
            </div>
            <button onclick="startTimedGame()" style="margin-top:15px;">开始游戏</button>
        </div>
    </div>
    <div id="wordrain" class="game-section">
        <!-- 单词雨游戏区域 -->
        <h2>单词雨</h2>
        <canvas id="wordrain-canvas" width="600" height="300"></canvas>
        <input id="wordrain-input" placeholder="输入单词消除..." oninput="wordRainInput()" disabled />
        <div id="wordrain-score">得分: 0</div>
        <button onclick="startWordRain()" style="margin-top:10px;">开始游戏</button>
    </div>
    <div id="react" class="game-section">
        <!-- 反应速度测试游戏区域 -->
        <h2>反应速度测试</h2>
        <div id="react-target-word" style="font-size:22px;margin-bottom:15px;"></div>
        <input id="react-input" placeholder="输入上方单词..." oninput="reactCheckInput()" disabled />
        <div id="react-stats">已完成: 0 / 10 | 总用时: 0 秒</div>
        <button onclick="startReactGame()" style="margin-top:10px;">开始游戏</button>
    </div>
    <div id="chain" class="game-section">
        <!-- 打字接龙游戏区域 -->
        <h2>打字接龙</h2>
        <div>当前单词：<span id="chain-current"></span></div>
        <input id="chain-input" placeholder="输入接龙单词..." oninput="chainCheckInput()" disabled />
        <div id="chain-score">得分: 0</div>
        <button onclick="startChainGame()" style="margin-top:10px;">开始游戏</button>
    </div>
    <div id="clear" class="game-section">
        <!-- 消除方块游戏区域 -->
        <h2>消除方块</h2>
        <div id="clear-blocks" style="margin-bottom:10px;"></div>
        <input id="clear-input" placeholder="输入上方单词消除..." oninput="clearCheckInput()" disabled />
        <div id="clear-score">得分: 0</div>
        <button onclick="startClearGame()" style="margin-top:10px;">开始游戏</button>
    </div>
    <div id="mole" class="game-section">
        <!-- 打地鼠游戏区域 -->
        <h2>打地鼠</h2>
        <div id="mole-area" style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:10px;"></div>
        <input id="mole-input" placeholder="输入出现的单词..." oninput="moleCheckInput()" disabled />
        <div id="mole-score">得分: 0</div>
        <button onclick="startMoleGame()" style="margin-top:10px;">开始游戏</button>
    </div>
    <script>
        // 检查是否已登录，未登录则跳转到登录页
        if (!localStorage.getItem('isLoggedIn')) { window.location.href = 'login.html'; }
        /**
         * 切换显示不同的游戏区域
         * @param {string} game - 游戏区域id
         */
        function showGame(game) {
            document.querySelectorAll('.game-section').forEach(div => div.classList.remove('active'));
            document.getElementById(game).classList.add('active');
            document.querySelectorAll('.game-menu button').forEach(btn => btn.classList.remove('active'));
            document.getElementById('btn-' + game).classList.add('active');
        }
        /**
         * 限时打字相关变量和函数
         */
        const timedSampleTexts = [
            "JavaScript is a lightweight interpreted programming language.",
            "Front-end development requires mastering HTML, CSS, and JavaScript.",
            "This typing practice system can help you improve your coding speed.",
            "Regular practice is the best way to improve typing speed.",
            "The art of programming is the art of dealing with complexity."
        ];
        let timedStart, timedTimer, timedOriginal = "", timedRunning = false;
        /**
         * 开始限时打字游戏，初始化数据和界面
         */
        function startTimedGame() {
            clearInterval(timedTimer);
            timedRunning = true;
            timedOriginal = timedSampleTexts[Math.floor(Math.random() * timedSampleTexts.length)];
            document.getElementById("timed-target-text").textContent = timedOriginal;
            document.getElementById("timed-input-text").value = "";
            document.getElementById("timed-input-text").disabled = false;
            document.getElementById("timed-input-text").focus();
            document.getElementById("timed-timer").textContent = "60";
            document.getElementById("timed-speed").textContent = "0";
            document.getElementById("timed-accuracy").textContent = "0";
            timedStart = Date.now();
            timedTimer = setInterval(updateTimedTimer, 1000);
        }
        /**
         * 更新时间倒计时，每秒调用
         */
        function updateTimedTimer() {
            const elapsed = Math.floor((Date.now() - timedStart) / 1000);
            const left = 60 - elapsed;
            document.getElementById("timed-timer").textContent = left > 0 ? left : 0;
            if (left <= 0) {
                clearInterval(timedTimer);
                timedRunning = false;
                document.getElementById("timed-input-text").disabled = true;
            }
        }
        /**
         * 检查限时打字输入内容，计算速度和准确率
         */
        function timedCheckInput() {
            if (!timedRunning) return;
            const inputText = document.getElementById("timed-input-text").value;
            let correctCount = 0;
            for (let i = 0; i < inputText.length; i++) {
                if (inputText[i] === timedOriginal[i]) correctCount++;
            }
            const timeElapsed = 1;
            const accuracy = inputText.length > 0 ? Math.round((correctCount / inputText.length) * 100) : 0;
            const speed = Math.round((inputText.length / 5) / timeElapsed) || 0;
            document.getElementById("timed-speed").textContent = speed;
            document.getElementById("timed-accuracy").textContent = accuracy;
        }
        /**
         * 单词雨相关变量和函数
         */
        const wordRainWords = ["apple","banana","orange","hello","world","javascript","typing","speed","rain","game","code","cloud","mouse","keyboard","screen","window","sky","blue","green","red","yellow"];
        let wordRainCanvas, wordRainCtx, wordRainDrops = [], wordRainScore = 0, wordRainInterval, wordRainRunning = false;
        /**
         * 开始单词雨游戏，初始化数据和界面
         */
        function startWordRain() {
            wordRainCanvas = document.getElementById('wordrain-canvas');
            wordRainCtx = wordRainCanvas.getContext('2d');
            wordRainDrops = [];
            wordRainScore = 0;
            document.getElementById('wordrain-score').textContent = '得分: 0';
            document.getElementById('wordrain-input').value = '';
            document.getElementById('wordrain-input').disabled = false;
            wordRainRunning = true;
            for(let i=0;i<5;i++) addWordRainDrop();
            wordRainInterval = setInterval(wordRainTick, 50);
        }
        /**
         * 添加一个新的下落单词
         */
        function addWordRainDrop() {
            const word = wordRainWords[Math.floor(Math.random() * wordRainWords.length)];
            wordRainDrops.push({word, x:Math.random()*520+20, y:0, speed:Math.random()*2+1});
        }
        /**
         * 单词雨动画主循环，处理下落和消除
         */
        function wordRainTick() {
            wordRainCtx.clearRect(0,0,600,300);
            wordRainDrops.forEach(drop => {
                drop.y += drop.speed;
                wordRainCtx.fillStyle = '#fff';
                wordRainCtx.font = '20px Arial';
                wordRainCtx.fillText(drop.word, drop.x, drop.y);
            });
            // 检查掉落
            for(let i=wordRainDrops.length-1;i>=0;i--) {
                if(wordRainDrops[i].y > 300) {
                    wordRainDrops.splice(i,1);
                    addWordRainDrop();
                }
            }
        }
        /**
         * 检查输入框内容，消除对应单词
         */
        function wordRainInput() {
            const val = document.getElementById('wordrain-input').value.trim();
            for(let i=0;i<wordRainDrops.length;i++) {
                if(wordRainDrops[i].word === val) {
                    wordRainDrops.splice(i,1);
                    addWordRainDrop();
                    wordRainScore++;
                    document.getElementById('wordrain-score').textContent = '得分: ' + wordRainScore;
                    document.getElementById('wordrain-input').value = '';
                    break;
                }
            }
        }
        /**
         * 反应速度测试相关变量和函数
         */
        const reactWords = ["apple","banana","orange","hello","world","javascript","typing","speed","rain","game","code","cloud","mouse","keyboard","screen","window","sky","blue","green","red","yellow"];
        let reactIndex = 0, reactStart = 0, reactTotalTime = 0, reactRunning = false;
        /**
         * 开始反应速度测试，初始化数据和界面
         */
        function startReactGame() {
            reactIndex = 0;
            reactTotalTime = 0;
            document.getElementById('react-input').value = '';
            document.getElementById('react-input').disabled = false;
            document.getElementById('react-stats').textContent = '已完成: 0 / 10 | 总用时: 0 秒';
            reactRunning = true;
            showNextReactWord();
        }
        /**
         * 显示下一个测试单词
         */
        function showNextReactWord() {
            if(reactIndex >= 10) {
                document.getElementById('react-input').disabled = true;
                document.getElementById('react-target-word').textContent = '测试完成！总用时: ' + reactTotalTime + ' 秒';
                reactRunning = false;
                return;
            }
            const word = reactWords[Math.floor(Math.random() * reactWords.length)];
            document.getElementById('react-target-word').textContent = word;
            document.getElementById('react-input').value = '';
            reactStart = Date.now();
        }
        /**
         * 检查反应速度输入内容，统计用时
         */
        function reactCheckInput() {
            if(!reactRunning) return;
            const word = document.getElementById('react-target-word').textContent;
            const val = document.getElementById('react-input').value.trim();
            if(val === word) {
                const used = ((Date.now() - reactStart)/1000).toFixed(2);
                reactTotalTime += parseFloat(used);
                reactIndex++;
                document.getElementById('react-stats').textContent = `已完成: ${reactIndex} / 10 | 总用时: ${reactTotalTime} 秒`;
                showNextReactWord();
            }
        }
        /**
         * 打字接龙相关变量和函数
         */
        const chainWords = ["apple","elephant","tiger","rabbit","table","egg","grape","ear","rose","eagle","dog","goat","top","pen","nose","ear","rat","tree","eggplant","tomato","owl"];
        let chainCurrent = "", chainScore = 0, chainRunning = false;
        /**
         * 开始打字接龙，初始化数据和界面
         */
        function startChainGame() {
            chainScore = 0;
            chainRunning = true;
            chainCurrent = chainWords[Math.floor(Math.random() * chainWords.length)];
            document.getElementById('chain-current').textContent = chainCurrent;
            document.getElementById('chain-input').value = '';
            document.getElementById('chain-input').disabled = false;
            document.getElementById('chain-score').textContent = '得分: 0';
        }
        /**
         * 检查接龙输入内容，判断是否接对
         */
        function chainCheckInput() {
            if (!chainRunning) return;
            const val = document.getElementById('chain-input').value.trim().toLowerCase();
            if (val && val[0] === chainCurrent[chainCurrent.length-1]) {
                chainCurrent = val;
                chainScore++;
                document.getElementById('chain-current').textContent = chainCurrent;
                document.getElementById('chain-score').textContent = '得分: ' + chainScore;
                document.getElementById('chain-input').value = '';
            }
        }
        /**
         * 消除方块相关变量和函数
         */
        const clearWords = ["apple","banana","orange","hello","world","javascript","typing","speed","rain","game","code","cloud","mouse","keyboard","screen","window","sky","blue","green","red","yellow"];
        let clearBlocks = [], clearScore = 0, clearRunning = false;
        /**
         * 开始消除方块，初始化数据和界面
         */
        function startClearGame() {
            clearBlocks = [];
            clearScore = 0;
            clearRunning = true;
            for(let i=0;i<6;i++) clearBlocks.push(clearWords[Math.floor(Math.random()*clearWords.length)]);
            renderClearBlocks();
            document.getElementById('clear-input').value = '';
            document.getElementById('clear-input').disabled = false;
            document.getElementById('clear-score').textContent = '得分: 0';
        }
        /**
         * 渲染方块区域
         */
        function renderClearBlocks() {
            const area = document.getElementById('clear-blocks');
            area.innerHTML = clearBlocks.map(w=>`<span style='display:inline-block;background:#007bff;color:#fff;padding:8px 16px;border-radius:6px;margin:2px;'>${w}</span>`).join('');
        }
        /**
         * 检查消除方块输入内容，消除对应方块
         */
        function clearCheckInput() {
            if (!clearRunning) return;
            const val = document.getElementById('clear-input').value.trim();
            const idx = clearBlocks.indexOf(val);
            if(idx !== -1) {
                clearBlocks.splice(idx,1);
                clearScore++;
                renderClearBlocks();
                document.getElementById('clear-score').textContent = '得分: ' + clearScore;
                document.getElementById('clear-input').value = '';
                if(clearBlocks.length === 0) {
                    document.getElementById('clear-input').disabled = true;
                }
            }
        }
        /**
         * 打地鼠相关变量和函数
         */
        const moleWords = ["apple","banana","orange","hello","world","javascript","typing","speed","rain","game","code","cloud","mouse","keyboard","screen","window","sky","blue","green","red","yellow"];
        let moleActive = [], moleScore = 0, moleRunning = false, moleInterval;
        /**
         * 开始打地鼠，初始化数据和界面
         */
        function startMoleGame() {
            moleActive = [];
            moleScore = 0;
            moleRunning = true;
            document.getElementById('mole-input').value = '';
            document.getElementById('mole-input').disabled = false;
            document.getElementById('mole-score').textContent = '得分: 0';
            renderMoleArea();
            if(moleInterval) clearInterval(moleInterval);
            moleInterval = setInterval(moleTick, 1200);
        }
        /**
         * 渲染地鼠区域
         */
        function renderMoleArea() {
            const area = document.getElementById('mole-area');
            area.innerHTML = '';
            for(let i=0;i<8;i++) {
                const word = moleActive[i] || '';
                area.innerHTML += `<span style='display:inline-block;width:80px;height:40px;line-height:40px;text-align:center;background:#eee;border-radius:6px;font-size:16px;margin:2px;'>${word}</span>`;
            }
        }
        /**
         * 地鼠动画主循环，定时出现新单词
         */
        function moleTick() {
            if(!moleRunning) return;
            if(moleActive.length < 8) moleActive.push(moleWords[Math.floor(Math.random()*moleWords.length)]);
            if(moleActive.length > 8) moleActive = moleActive.slice(-8);
            renderMoleArea();
        }
        /**
         * 检查打地鼠输入内容，消除对应单词
         */
        function moleCheckInput() {
            if (!moleRunning) return;
            const val = document.getElementById('mole-input').value.trim();
            const idx = moleActive.indexOf(val);
            if(idx !== -1) {
                moleActive[idx] = '';
                moleScore++;
                renderMoleArea();
                document.getElementById('mole-score').textContent = '得分: ' + moleScore;
                document.getElementById('mole-input').value = '';
            }
        }
    </script>
</body>
</html> 